﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Win32;

namespace RemoteScriptingLibrary
{
    public class RegistryHelper
    {
        public static void SearchSubKeys(RegistryKey root, string sSearchKey)
        {
            SearchSubKeys(root, sSearchKey, false);
        }

        public static void SearchSubKeys(RegistryKey root, string sSearchKey, bool _bUseRegex)
        {
            bool containsKey = false;
            foreach (string sKeyname in root.GetSubKeyNames())
            {
                try
                {
                    using (RegistryKey key = root.OpenSubKey(sKeyname))
                    {
                        if (_bUseRegex)
                        {
                            if (Regex.Match(sKeyname, sSearchKey).Success)
                            {
                                containsKey = true;
                            }
                        }
                        else
                        {
                            if (sKeyname.Contains(sSearchKey))
                            {
                                containsKey = true;
                            }
                        }

                        if (containsKey)
                        {
                            GenerateKeyNameOutputEvent(sKeyname);
                            containsKey = false;
                        }
                        SearchSubKeys(key, sSearchKey);
                    }
                }
                catch (System.Security.SecurityException)
                {
                }
                catch (System.IO.IOException)
                {
                }
            }
            if (containsKey)
            {
                //    using (RegistryKey key = root.CreateSubKey("Device Parameters"))
                //    {
                //        key.SetValue("ShowInShell", /* your value */, RegistryValueKind.DWord);
                //    }
            }
        }

        private static void GenerateKeyNameOutputEvent(string sKeyname)
        {
            ScriptCommands.Script.OutputEvent(new ScriptCommands.Script.OutputEventArgs(sKeyname + Environment.NewLine));
        }
    }
}
